package org.ichow.question.plugins
{
	import flash.text.TextField;
	import mx.utils.StringUtil;
	import org.ichow.debug.Debug;
	
	/**
	 * ...
	 * FillIn 填空
	 * 0908 更新一个空格多个答案
	 * @author M.ichow
	 */
	
	public class FillInPlugin extends QuestionPlugin
	{
		public static const VERSION : Number = 1.0;
		public static const API : Number = 1.0;
		// textfield array
		protected var tfs : Vector.<TextField>
		// is check all
		protected var checkAll : Boolean = false;
		
		public function FillInPlugin()
		{
			this.propName = "FillInPlugin";
			optionName = "a_$_txt";
		}
		
		// ----- protected methods ----- //
		
		override protected function init() : void
		{
			super.init();
			checkAll = getData( "checkAll" ) as Boolean;
			tfs = new Vector.<TextField>();
			for ( var i : int = 0 ; i < options ; i++ )
			{
				var n : String = optionName.replace( "$" , i );
				var tf : TextField = getChild( n ) as TextField;
				if ( tf )
				{
					tf.text = "";
					tfs.push( tf );
				}
			}
		}
		
		// Public Methods //
		
		override public function active() : void
		{
			super.active();
			for ( var i : int = 0 , len : int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].mouseEnabled = true;
			}
		}
		
		override public function cancel() : void
		{
			super.cancel();
			for ( var i : int = 0 , len : int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].mouseEnabled = false;
			}
		}
		
		/**
		 *
		 * @return
		 */
		override public function check() : Boolean
		{
			for ( var i : int = 0 , len : int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] && !_check( tfs[ i ].text , answer[ i ] ) )
				{
					return false;
				}
			}
			return true;
		}
		
		/**
		 * 获取得分
		 */
		override public function get score() : Number
		{
			_score = 0;
			if ( checkAll )
				return check() ? tScore : 0;
			
			for ( var i : int = 0 , len : int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] && _check( tfs[ i ].text , answer[ i ] ) )
					_score += ( tScore / len );
			}
			return _score;
		}
		
		/**
		 * 0908 根据答案类型检查
		 * @param	txt
		 * @param	ans
		 * @return
		 */
		protected function _check( txt : String , ans : Object ) : Boolean
		{
			txt = StringUtil.trim( txt );
			//fill many
			if ( ans is Array )
			{
				if (( ans as Array ).indexOf( txt ) == -1 )
					return false;
			}
			else
			{
				if ( StringUtil.trim( String( ans ) ) != txt )
					return false;
			}
			return true;
		}
		
		/**
		 * 重置
		 */
		override public function reset() : void
		{
			super.reset();
			for ( var i : int = 0 , len : int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].text = "";
			}
		}
	
	}

}